#include "../common/message.hpp"
#include "../common/net.hpp"
#include "../common/dispatcher.hpp"
#include "../server/rpc_router.hpp"

// void onRpcRequest(const bitrpc::BaseConnection::ptr &conn, bitrpc::RpcRequest::ptr &msg)
// {
//     std::cout << "收到了Rpc请求: " << msg->method() << std::endl;
//     std::string body = msg->serialize();
//     std::cout << body << std::endl;
//     std::cout << "method: " << msg->method() << std::endl;
//     auto rpc_res = bitrpc::MessageFactory::create<bitrpc::RpcResponse>();
//     rpc_res->setId("11111");
//     rpc_res->setMType(bitrpc::MType::RSP_RPC);
//     rpc_res->setRCode(bitrpc::RCode::RCODE_OK);
//     rpc_res->setResult(33);
//     conn->send(rpc_res);
// }

// void OnTopicRequest(const bitrpc::BaseConnection::ptr &conn, bitrpc::TopicRequest::ptr &msg)
// {
//     std::cout << "收到了Rpc请求: " << msg->method() << std::endl;
//     std::string body = msg->serialize();
//     std::cout << body << std::endl;
//     auto rpc_res = bitrpc::MessageFactory::create<bitrpc::RpcResponse>();
//     rpc_res->setId("22222");
//     rpc_res->setMType(bitrpc::MType::RSP_TOPIC);
//     rpc_res->setRCode(bitrpc::RCode::RCODE_OK);
//     conn->send(rpc_res);
// }

void Add(const Json::Value &req, Json::Value &rsp)
{
    int num1 = req["num1"].asInt();
    int num2 = req["num2"].asInt();
    rsp = num1 + num2;
}

int main()
{
    auto router = std::make_shared<bitrpc::server::RpcRouter>();
    std::unique_ptr<bitrpc::server::SDescribeFactory> desc_factory(new bitrpc::server::SDescribeFactory());
    desc_factory->setMethodName("Add");
    desc_factory->setParamsDesc("num1", bitrpc::server::VType::INTEGRAL);
    desc_factory->setParamsDesc("num2", bitrpc::server::VType::INTEGRAL);
    desc_factory->setReturnType(bitrpc::server::VType::INTEGRAL);
    desc_factory->setCallback(Add);
    router->registerMethod(desc_factory->build());

    auto cb = std::bind(&bitrpc::server::RpcRouter::onRpcRequest, router.get(), std::placeholders::_1, std::placeholders::_2);

    // 给dispather中的onMessage设置一个回调
    auto dispather = std::make_shared<bitrpc::Dispatcher>();
    dispather->registerHandler<bitrpc::RpcRequest>(bitrpc::MType::REQ_RPC, cb);

    // 用dispather中的onMessgae 给server设置一个回调
    auto server = bitrpc::ServerFactory::create(9090);
    auto message_cb = std::bind(&bitrpc::Dispatcher::onMessage, dispather.get(), std::placeholders::_1, std::placeholders::_2);
    server->setMessageCallback(message_cb);
    server->start();
    return 0;
}